package com.community.common.security.resolver;

import com.alibaba.fastjson.JSON;
import com.community.common.security.dto.UserLoginDto;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    // 这个方法会true下面的方法才会执行
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 判断当前方法的参数类型是否是UserLoginDto
        return parameter.getParameterType().isAssignableFrom(UserLoginDto.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String userInfo = requestAttributes.getRequest().getHeader("userInfo");
        return JSON.parseObject(userInfo,UserLoginDto.class);
    }
}
